package com.vogue.supplymall.common.domain.tool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * Created by tyc on 2017-12-4.
 * Gson相关方法类
 */
public class GsonUtils {
	public static Gson GSON = new Gson();
	public static Gson GSON_DATEFORMATE = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
	public static Gson GSON_EXPOSE = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); 
	public static Gson GSON_EXPOSE_DATEFORMATE = new GsonBuilder().setDateFormat("yyyy-MM-dd").excludeFieldsWithoutExposeAnnotation().create(); 	
	public static Gson GSON_EXPOSE_DATEFORMATE_HMS = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); 
	
	/**
	 * ajax方式输出json串
	 * @param response
	 * @param json
	 * @throws IOException
	 */
	public static void ajaxJson(HttpServletResponse response,String json) throws IOException{
	    response.setContentType("application/json;charset=utf-8");
	    response.setHeader("Accept-Encoding", "gzip,deflate");
		PrintWriter out = response.getWriter();  
        out.write(json); 
        out.flush();
        out.close();
	}
	
	/**
	 * 获取post参数，处理inputStream类</br>
	 * tyc</br>
	 * 2017-12-06
	 */

	public static String getPostFrominputStream(InputStream is,String charset) throws Exception{
		String resultStr="";
		InputStreamReader isr=null;
		BufferedReader br=null;
		StringBuffer sb=null;
		String line=null;
			
		try {
			isr=new InputStreamReader(is, charset);
			br=new BufferedReader(isr);
			sb=new StringBuffer();
			while((line=br.readLine())!=null) {
				sb.append(line+"/n");
			}
			resultStr=sb.toString();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			if(br!=null) {
				br.close();
			}
			if(isr!=null) {
				isr.close();
			}
			if(is!=null) {
				is.close();
			}
		}
		
		return resultStr;
	}
}
